<template>
  <div>
    <el-dialog
      title="编辑患者"
      :visible.sync="dialogVisiblePatient"
      fullscreen
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="cancel"
      :before-close="beforeClose"
    >
      <p class="title_box">基本信息</p>
      <el-row>
        <p class="title_box_1">个人信息</p>
        <el-col :span="8">
          <el-form
            :model="ruleForm1"
            :rules="rules1"
            ref="ruleForm1"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="姓名" prop="patientName">
              <el-input v-model="ruleForm1.patientName" />
            </el-form-item>
            <el-form-item label="用户编号">
              <el-input v-model="ruleForm1.medicalRecordNum" />
            </el-form-item>
            <el-form-item label="出生日期" prop="birthday">
              <el-date-picker
                v-model="ruleForm1.birthday"
                type="date"
                placeholder="选择出生日期"
                @change="changeDate"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions1"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="ruleForm1.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="身份证号"
              prop="identificationCard"
              :rules="[
                {
                  required: true,
                  message: '身份证号不能为空',
                  trigger: 'blur'
                },
                {
                  pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                  message: '身份证号格式不正确',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input v-model="ruleForm1.identificationCard" @blur="blurIdentificationCard"/>
            </el-form-item>
            <el-form-item label="工作单位">
              <el-input v-model="ruleForm1.workUnit" />
            </el-form-item>
            <p class="title_box_1">联系方式</p>
            <el-form-item
              label="电话"
              prop="patientPhone"
              :rules="[
                {
                  required: true,
                  message: '电话不能为空',
                  trigger: 'blur'
                },
                {
                  min: 11,
                  max: 11,
                  message: '长度11个数字',
                  trigger: 'blur'
                },
                {
                  pattern: /^((0\d{2,3}-\d{7,8})|(1[356789]\d{9}))$/,
                  message: '手机号格式不正确',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input v-model="ruleForm1.patientPhone" />
            </el-form-item>
            <el-form-item
              label="联系人电话"
              prop="linkPhone"
              :rules="[
                {
                  required: true,
                  message: '电话不能为空',
                  trigger: 'blur'
                },
                {
                  min: 11,
                  max: 11,
                  message: '长度11个数字',
                  trigger: 'blur'
                },
                {
                  pattern: /^((0\d{2,3}-\d{7,8})|(1[356789]\d{9}))$/,
                  message: '手机号格式不正确',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input v-model="ruleForm1.linkPhone" />
            </el-form-item>
            <p class="title_box_1">患者信息</p>
            <el-form-item label="患者来源">
              <el-select style="width: 100%" v-model="ruleForm1.patientSource">
                <el-option
                  :label="item.dictName"
                  :value="+item.dictValue"
                  v-for="(item, index) in sysUserSexerm_patient_sourceOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="过敏史" prop="allergyHistory">
              <el-input v-model="ruleForm1.allergyHistory" />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-form
            :model="ruleForm2"
            :rules="rules2"
            ref="ruleForm2"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="年龄">
              <el-input v-model="ruleForm2.age" disabled />
            </el-form-item>
            <!-- <el-form-item label="昵称">
              <el-input v-model="ruleForm2.nickName" />
            </el-form-item> -->
            <el-form-item label="民族">
              <el-select style="width: 100%" v-model="ruleForm2.nationality">
                <el-option
                  :label="item.dictLabel"
                  :value="item.dictLabel"
                  v-for="(item, index) in sysUserSexerm_nationalityOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职业">
              <el-select style="width: 100%" v-model="ruleForm2.occupation">
                <el-option
                  :label="item.dictName"
                  :value="item.dictValue"
                  v-for="(item, index) in sysUserSexerm_occupationOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="国籍">
              <el-select style="width: 100%" v-model="ruleForm3.citizenship">
                <el-option
                  :label="item.dictLabel"
                  :value="item.dictLabel"
                  v-for="(item, index) in sysUserSexerm_citizenshipOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="血型">
              <el-select style="width: 100%" v-model="ruleForm3.bloodGroup">
                <el-option
                  :label="item.dictLabel"
                  :value="item.dictLabel"
                  v-for="(item, index) in sysUserSexerm_patient_bloodOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="婚姻状况">
              <el-select style="width: 100%" v-model="ruleForm3.marriage">
                <el-option
                  :label="item.dictName"
                  :value="item.dictValue"
                  v-for="(item, index) in sysUserSexerm_marriageOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <p class="title_box_1" style="height: 21px"></p>

            <el-form-item label="家庭住址">
              <el-input v-model="ruleForm2.homeAddress" />
            </el-form-item>
            <el-form-item label="与患者关系">
              <el-select
                style="width: 100%"
                v-model="ruleForm2.personalRelationship"
              >
                <el-option
                  :label="item.dictName"
                  :value="item.dictValue"
                  v-for="(
                    item, index
                  ) in sysUserSexerm_personal_relationshipOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>

            <p class="title_box_1" style="height: 21px"></p>

            <el-form-item label="患者标签" prop="patientTags">
              <el-select style="width: 100%" v-model="ruleForm2.patientTags">
                <el-option
                  :label="item.dictName"
                  :value="item.dictValue"
                  v-for="(item, index) in sysUserSexerm_patient_tagsOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="既往史" prop="pastHistory">
              <el-select
                style="width: 100%"
                multiple
                v-model="ruleForm2.pastHistory"
              >
                <el-option
                  :label="item.dictName"
                  :value="item.dictValue"
                  v-for="(item, index) in sysUserSexerm_past_historyOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-form
            :model="ruleForm3"
            :rules="rules3"
            ref="ruleForm3"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户头像：">
              <el-upload
                :before-upload="beforeUpload"
                ref="uploadRef"
                action="#"
                list-type="picture-card"
                :http-request="handlePictureCardPreview"
                :on-remove="handleRemove"
                :file-list="imgFileList"
                :on-change="handleChange"
                accept=".jpg,.jpeg,.png,.gif,.tif,.bmp,.svg,.jpg,"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog
                :visible.sync="dialogImgVisible"
                v-if="dialogImgVisible"
              >
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
            <p class="title_box_1" style="height: 36px"></p>
            <p class="title_box_1" style="height: 36px"></p>
            <p class="title_box_1" style="height: 36px"></p>
            <p class="title_box_1" style="height: 36px"></p>
            <p class="title_box_1" style="height: 36px"></p>
            <p class="title_box_1" style="height: 21px"></p>
            <p class="title_box_1" style="height: 21px"></p>
            <p class="title_box_1" style="height: 21px"></p>
            <el-form-item label="家族史" prop="familyHistory">
              <el-select
                style="width: 100%"
                multiple
                v-model="ruleForm3.familyHistory"
              >
                <el-option
                  :label="item.dictName"
                  :value="item.dictValue"
                  v-for="(item, index) in sysUserSexerm_family_historyOptions"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" @click="submit">保存患者</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { upload } from '@/api/system/user.js'
import {
  sysUserSexerm_citizenship,
  sysUserSexerm_nationality,
  sysUserSexerm_patient_blood,
  patientAdd,
  dropdownList
} from '@/api/allApi.js'
export default {
  name: 'EitcErmPcAddDialog',
  props: {
    tableForm: {
      type: Object,
      default: {}
    },
    dialogVisiblePatient: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      ruleForm1: {
        sex: '1'
      },
      rules1: {
        patientName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        medicalRecordNum: [
          { required: true, message: '请输入病历号', trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: '请选择出生日期', trigger: 'change' }
        ],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        identificationCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
        ],
        patientPhone: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ],
        linkPhone: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' }
        ],
        allergyHistory: [
          { required: true, message: '请输入过敏史', trigger: 'blur' }
        ]
      },
      ruleForm2: {
        patientType: '1'
      },
      rules2: {
        patientType: [
          { required: true, message: '请选择患者类型', trigger: 'change' }
        ],
        age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
        personalRelationship: [
          { required: true, message: '请选择与患者关系', trigger: 'change' }
        ],
        patientTags: [
          { required: true, message: '请选择患者标签', trigger: 'change' }
        ],
        pastHistory: [
          { required: true, message: '请选择既往史', trigger: 'change' }
        ]
      },
      ruleForm3: {
        avatar: ''
      },
      rules3: {
        familyHistory: [
          { required: true, message: '请选择家族史', trigger: 'change' }
        ]
      },
      dialogImageUrl: '',
      dialogImgVisible: false,
      imgFileList: [],
      imgFileFlag: 'imgFileList',
      fileType: ['png', 'jpg', 'jpeg', 'gif'],

      sysUserSexerm_citizenshipOptions: [], // 国籍
      sysUserSexerm_occupationOptions: [], // 职业
      sysUserSexerm_nationalityOptions: [], // 民族
      sysUserSexerm_marriageOptions: [], // 婚姻
      sysUserSexerm_patient_sourceOptions: [], // 患者来源
      sysUserSexerm_family_historyOptions: [], // 家族史
      sysUserSexerm_past_historyOptions: [], // 既往史
      sysUserSexerm_patient_tagsOptions: [], // 患者标签
      sysUserSexerm_patient_bloodOptions: [], // 血型
      sysUserSexerm_personal_relationshipOptions: [] // 与本人关系
    }
  },

  mounted() {
    this.initOptions()
    this.initDropdownList()
    this.ruleForm1 = this.tableForm
    this.ruleForm2 = this.tableForm
    this.ruleForm3 = this.tableForm
    if(this.tableForm.pastHistory){
      this.ruleForm2.pastHistory = this.tableForm.pastHistory.split(',')
    }
    if(this.tableForm.familyHistory){
      this.ruleForm3.familyHistory = this.tableForm.familyHistory.split(',')
    }

    if (this.tableForm.avatar) {
      this.dialogImageUrl = this.baseUrl + this.tableForm.avatar
      this.imgFileList.push({
        uid: Date.now(),
        url: this.baseUrl + this.tableForm.avatar,
        name: '封面'
      })
      this.$nextTick(() => {
        if (this.imgFileList.length > 0) {
          this.$refs.uploadRef.$el.children[1].style.display = 'none'
        } else {
          this.$refs.uploadRef.$el.children[1].style.display = 'block'
        }
      })
    }
    
    this.blurIdentificationCard()
    this.$forceUpdate()
  },

  methods: {
    cancel() {
      this.$emit('cancelAll', '1')
    },
    beforeClose() {
      this.$confirm('确认退出吗？退出将不会保留当前填写数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$emit('cancelAll', '1')
        })
        .catch((err) => {
          err
        })
    },
    submit() {
      this.$refs.ruleForm1.validate((valid) => {
        if (valid) {
          this.$refs.ruleForm2.validate((valid) => {
            if (valid) {
              this.$refs.ruleForm3.validate(async (valid) => {
                if (valid) {
                  this.ruleForm2.pastHistory = this.tableForm.pastHistory.join()
                  this.ruleForm3.familyHistory =
                    this.tableForm.familyHistory.join()
                  let obj = {
                    ...this.ruleForm1,
                    ...this.ruleForm2,
                    ...this.ruleForm3
                  }
                  const res = await patientAdd(obj)
                  if (res.code != 200) return this.$message.error(res.msg)
                  this.$message.success('编辑成功')
                  this.$emit('cancelAll', '1')
                }
              })
            }
          })
        }
      })
    },
    changeDate(inputDateString) {
      // 将输入的日期字符串转换为日期对象
      var inputDate = new Date(inputDateString)
      // 如果输入的日期无效，则返回null
      if (isNaN(inputDate.getTime())) {
        return null
      }
      // 计算当前日期与输入日期之间的差值
      var today = new Date()
      var age = today.getFullYear() - inputDate.getFullYear()
      // 如果今年的日期还没过输入日期的生日，则年龄减1
      if (
        today.getMonth() < inputDate.getMonth() ||
        (today.getMonth() == inputDate.getMonth() &&
          today.getDate() < inputDate.getDate())
      ) {
        age--
      }
      this.ruleForm2.age = age
      this.$forceUpdate()
    },
    // 上传前loading加载
    beforeUpload(file) {
      let isImg = false
      if (this.fileType.length) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
      } else {
        isImg = file.type.indexOf('image') > -1
      }

      if (!isImg) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`
        )
        return false
      }
      return true
    },
    handleRemove(file, fileList) {
      this.imgFileList = fileList
      this.dialogImageUrl = ''
      if (!fileList.length) {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'block'
        this.imgFileFlag = 'imgFileList'
        this.ruleForm3.avatar = ''
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImgVisible = true
    },
    handleChange(file, fileList) {
      // 当上传图片成功时，即隐藏上传按钮
      if (fileList.length > 0) {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'none'
      } else {
        this.$refs.uploadRef.$el.children[
          this.$refs.uploadRef.$el.children.length - 1
        ].style.display = 'block'
      }
    },
    // 封面上传
    async handlePictureCardPreview(file) {
      try {
        if (!file) return this.$message.error('文件有误')
        const formData = new FormData()
        formData.append('file', file.file)
        const res = await upload(formData)
        this.dialogImageUrl = res.url
        this.$nextTick(() => {
          this.dialogVisible = true
        })
        if (res.code !== 200) {
          this.ruleForm.imgFileList = []
          return this.$message.error('文件格式不支持')
        }
        this.ruleForm3.avatar = res.fileName
      } catch (error) {
        this.ruleForm.imgFileList = []
      }
    },
    async initOptions() {
      const res1 = await sysUserSexerm_citizenship()
      const res3 = await sysUserSexerm_nationality()
      const res10 = await sysUserSexerm_patient_blood()

      this.sysUserSexerm_citizenshipOptions = res1.data
      this.sysUserSexerm_nationalityOptions = res3.data
      this.sysUserSexerm_patient_bloodOptions = res10.data
    },
    async initDropdownList() {
      const res1 = await dropdownList('erm_patient_tags') // 患者标签
      const res2 = await dropdownList('erm_patient_source') // 患者来源
      const res3 = await dropdownList('erm_personal_relationship') // 与患者关系
      const res4 = await dropdownList('erm_past_history') // 既往史
      const res5 = await dropdownList('erm_marriage') // 婚姻状况
      const res6 = await dropdownList('erm_family_history') // 家族史
      const res7 = await dropdownList('erm_occupation') // 职业

      this.sysUserSexerm_patient_tagsOptions = res1.data
      this.sysUserSexerm_patient_sourceOptions = res2.data
      this.sysUserSexerm_personal_relationshipOptions = res3.data
      this.sysUserSexerm_past_historyOptions = res4.data
      this.sysUserSexerm_marriageOptions = res5.data
      this.sysUserSexerm_family_historyOptions = res6.data
      this.sysUserSexerm_occupationOptions = res7.data

    },
    blurIdentificationCard(){
      let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if(reg.test(this.ruleForm1.identificationCard)){
       this.ruleForm2.age = this.getAgeFromIdCard(this.ruleForm1.identificationCard)
       this.$forceUpdate()
      }
    },
    getAgeFromIdCard(idCard) {
      if (idCard && idCard.length === 18) {
        const birthYear = parseInt(idCard.substring(6, 10), 10);
        const currentYear = new Date().getFullYear();
        return currentYear - birthYear;
      }
      return null; // 身份证号码不正确或者格式不对
    },
  }
}
</script>

<style lang="scss" scoped>
.title_box {
  font-size: 18px;
  font-weight: 700;
}
.title_box_1 {
  font-size: 16px;
  font-weight: 700;
}
</style>